<?php
App::uses('CakeEmail','Network/Email');
class UsersController extends AppController
{
				var $name = "Users" ;

				public $uses = array( 'Profile', 'User','FriendUser','Board','UserImageBoard','UserLike','UserComment','UserFollow' ) ;
				public function login()
				{
								if ( $this->Session->check( 'Auth.User' ) )
								{
												$this->redirect( array('controller'=>'UserImageBoards','action'=>'listImages' ) ) ;
								}

								// if we get the post information, try to authenticate
								if ( $this->request->is( 'post' ) )
								{
												if ( $this->Auth->login() )
												{
																$this->redirect( $this->Auth->redirectUrl() ) ;
												} else
												{
																$this->Session->setFlash( __( 'Invalid username or password' ) ) ;
												}
								}
				}

				public function logout()
				{
								return $this->redirect( $this->Auth->logout() ) ;
				}
  /*lấy tất cả các thông tin liên quan đến các board trong $boards*/
  public function getInfoBoards($boards = null){
    if($boards){
      for($i=0; $i<count($boards); $i++){
      $userImageBoard = $this->UserImageBoard->find('all',array(
                                  'conditions'=>array(
                                          'UserImageBoard.board_id'=>$boards[$i]['Board']['id']),
                                  'limit'=>5));
      $boards[$i]['ImageInBoard'] = $userImageBoard;
      /*boardAction =1,edit;2,follow;3,unfollow*/
      if($boards[$i]['Board']['user_id'] == $this->Auth->user('id')){
        $boards[$i]['boardAction'] = 1;
      }else
      if($this->UserFollow->find('all',array(
                    'conditions'=>array(
                      'UserFollow.user_id'=>$this->Auth->user('id'),
                      'UserFollow.board_id'=>$boards[$i]['Board']['id'])
                    ))){
        $boards[$i]['boardAction'] = 3;
      }else{
        $boards[$i]['boardAction'] = 2;
      }

      /*lay profile user cua board*/
      $user = $this->Profile->findByUser_id($boards[$i]['Board']['user_id']);
      $boards[$i]['Profile'] = $user['Profile'];
    }
    return $boards;
    }
  }

				public function view($userId = null)
				{
				    if($userId == null){
              $userId = $this->Auth->user('id');
            }
                     
                              $name=$this->User->find( 'first', array( 'conditions' =>
																array( 'User.id' => $this->Auth->user( 'id' ) ) ) ) ;
                              if (isset($this->params['requested']))
            {
               return $name;
            }   
								$this->set( 'name', $name) ;
                                
            $board=$this->Board->find('all',array('conditions'=>array('user_id'=>$userId)));
            if($board){
              $this->set('count_board',count($board));
              $boards = $this->getInfoBoards($board);
              $this->set('boards',$boards);
            }
            else{
              $this->set('count_board',0);
              $this->set('boards',$boards);
            }

            $img=$this->UserImageBoard->find('all',array('conditions'=>array('user_id'=>$userId)));
            
            if($img){
              $this->set('img',count($img));
            }else{
              $this->set('img',0);
            }
            
            
                               


				}

				public function register()
				{
								if ( ! empty( $this->request->data ) )
                                if($this->request->data['User']['password']==$this->request->data['User']['repassword']){
								{
												// Use the following to avoid validation errors:
												unset( $this->User->Profile->validate['user_id'] ) ;
                                                $user=$this->Profile->find('all');
                                                $use=$this->Profile->find('all',array('fields'=>'MAX(Profile.id) AS id','group by'=>'id'));
												pr($use);
                                                $dir = WWW_ROOT . 'img' ;
												$slas = '/' ;
                                                
                                                foreach($user as $us)
                                                    if($us['Profile']['avatar']==$this->request->data['Profile']['avatar']['name']){
												$filenamez = $use[0][0]['id'].$this->request->data['Profile']['avatar']['name'] ;
                                                break;
                                                }   else $filenamez = $this->request->data['Profile']['avatar']['name'];
												$dir = $dir . $slas . $filenamez ;
												echo $dir ;
												move_uploaded_file( $this->request->data['Profile']['avatar']['tmp_name'],
																$dir ) ;
												$this->request->data['Profile']['avatar'] =$filenamez;
												$this->request->data['Profile']['sex']=$this->request->data['Profile']['sex'][0];
												if( $this->request->data['Profile']['avatar'] =='')  
                                                  $this->request->data['Profile']['avatar'] ='anhnen.png';
                                                if ( $this->User->saveAssociated( $this->request->data ) ){
                                                  $userId = $this->User->findByUsername($this->request->data['User']['username']);
                                                  $this->createBoardDefault($userId['User']['id']);
                                                  $this->redirect( array( 'action' => 'login' ) ) ;
                                                }
																
								}

				} else $this->Session->setFlash('Repassword và Password phải trùng nhau');
}

  public function createBoardDefault($userId = null){
    if($userId){
      $board['Board']['user_id'] = $userId;
      $board['Board']['name'] = 'Default';
      $board['Board']['description'] ='this is board default';

      $this->Board->create();
      $this->Board->save($board);
    }
  }

 public function changepassword(){
   
    $user=$this->User->find( 'first', array( 'conditions' =>array('User.id'=>$this->Auth->user('id') )) );
    if(!$user){
        throw new NotFoundException('Không tồn tại User');
    }
    
     if(!$this->request->data) $this->request->data=$user;
    if($this->request->is(array('post','put'))){
        $this->User->id=$this->Auth->user('id');
        Security::setHash('md5');
        if(md5($this->request->data['User']['password'])!= $user['User']['password']){
            $this->Session->setFlash('Vui lòng nhập đúng mật khẩu hiện tại');    
            
        } else{
            
             $this->request->data['User']['password']=$this->request->data['User']['repassword'];
            if($this->User->save($this->request->data)){
                $this->Session->setFlash('Đổi mật khẩu thành công');
                $this->redirect(array('action'=>'view'));
            
            
            
            }
        }
        
    }
    
 }
function sendpassword(){
    if(!empty($this->request->data)){
       $user= $this->User->find('first',array('conditions'=>array('User.email'=>$this->request->data['User']['email'])));
       if(!$user){
        throw new NotFoundException('Không tồn tại User');
    }
        $email= new CakeEmail('smtp');
        $email->from(array('cuocdoi1993@gmail.com'=>'Web pinterest'))
              ->to($this->request->data['User']['email'])
              ->subject('Lấy lại mật khẩu');
              $str=$user['User']['password'];
              $str1= substr($str,1,8);
    if($email->send($str1)){
        $a='pinterest';
        $this->redirect(array('action'=>'updatepassword',$user['User']['id']));
    }
  }
}

 public function updatepassword($id=null){
    if(!$id){
        throw new NotFoundException('Không xác định được ID');
    }
    $user=$this->User->find( 'first', array( 'conditions' =>array('User.id'=>$id )) );
    if(!$user){
        throw new NotFoundException('Không tồn tại User');
    }
    if(!$this->request->data) $this->request->data=$user;
     $str=$user['User']['password'];
              $str1= substr($str,1,8);
    
     
     if($this->request->is('post')){
        $this->User->id=$id;
        $this->request->data['User']['password']=$str1;
        $this->request->data['User']['repassword']=$str1;
        if($this->User->save($this->request->data)){
            $this->Session->setFlash('Hãy vào Email của bạn để xem mật khẩu');
            $this->redirect(array('action'=>'login'));
        }else $this->Session->setFlash('Hãy vào Email');
        
     }
    
 }
 
 
 public function friend(){
     $name=$this->User->find( 'first', array( 'conditions' =>
																array( 'User.id' => $this->Auth->user( 'id' ) ) ) ) ;
								$this->set( 'name', $name) ;
                               
     $fr= $this->FriendUser->find('all',array('conditions'=>array('OR'=>array('friend_id'=>$this->Auth->user('id'),'user_id'=>$this->Auth->user('id')))));
    if(!$fr) $f=null;
    else
     foreach($fr as $fu){
        $f[]=$fu['FriendUser']['user_id'];
        $f[]=$fu['FriendUser']['friend_id'];
     } 
     if($f!=null){
          if($this->request->is('post')){
             if(!$this->request->data)
                 $friend=$this->User->find('all',array('conditions'=>array('not'=>array('User.id'=>$f))) );
             else  {$friend=$this->User->find('all',array('conditions' =>array('not'=>array('User.id'=>$f),'Profile.name LIKE'=>'%'.$this->request->data['Profile']['name'].'%')) );
                   if(!$friend)$friend=null;
          }}
          else $friend=$this->User->find('all',array('conditions' =>array('not'=>array('User.id'=>$f))) );}
     else
        if($this->request->is('post')){
        if(!$this->request->data)
     $friend=$this->User->find('all',array( 'conditions' =>array('User.id !='=>$this->Auth->user('id') )));
     else  {$friend=$this->User->find('all',array( 'conditions' =>array('User.id !='=>$this->Auth->user('id') ,'Profile.name LIKE'=>'%'.$this->request->data['Profile']['name'].'%')) );
            if(!$friend)$friend=null;
          }}
        else
        $friend=$this->User->find('all',array( 'conditions' =>array('User.id !='=>$this->Auth->user('id') )));
        
        if(!$friend)$friend=null;
     if (isset($this->params['requested']))
            {
               return $friend;
            }
            
        $this->set('friend',$friend);
        //$this->redirect(array('action'=>'index'));
      }
 
 public function listaddfriend(){
    	$this->set( 'name', $this->User->find( 'first', array( 'conditions' =>array('User.id' => $this->Auth->user( 'id' )) )  ) ) ;
    $fr = $this->FriendUser->find('all',array('conditions'=>array('friend_id'=>$this->Auth->user('id'),'status_flag'=>0)));
    if($fr){
    foreach($fr as $f)
        $fu[]=$f['FriendUser']['user_id'];
        $friend=$this->User->find('all',array('conditions'=>array('User.id'=>$fu)));}
        else $friend=null;
          if (isset($this->params['requested']))
            {
               return $friend;
            }
            
    $this->set('friend',$friend);
    
 }
 public function count(){
    $fr=$this->FriendUser->find('all',array('conditions'=>array('friend_id'=>$this->Auth->user('id'),'status_flag'=>0)));
    $c=count($fr);
    if(isset($this->params['requested'])){
      return $c;  
    }
 $this->set('fr',$c);
 }
 public function listfriend(){
    $name=$this->User->find( 'first', array( 'conditions' =>
																array( 'User.id' => $this->Auth->user( 'id' ) ) ) ) ;
    $fr = $this->FriendUser->find('all',array('conditions'=>array('OR'=>array('friend_id'=>$this->Auth->user('id'),'user_id'=>$this->Auth->user('id')),
    'status_flag'=>1)));
    if($fr){
       foreach ($fr as $f){
            $lf[]=$f['FriendUser']['user_id'];
            $lf[]=$f['FriendUser']['friend_id'];
        }
    
        $list=$this->User->find('all',array('conditions'=>array('User.id'=>$lf,'User.id !='=>$this->Auth->user('id'))));
        //pr($list);
      } else $list=null;
      if(isset($this->params['requested'])){
      return $list;  
    }
      $this->set('list',$list);
      $this->set('name',$name);
         }
 public function updateprofile()
    {
    
        $post = $this->User->findById($this->Auth->user('id'));
        if (!$post)
        {
            throw new NotFoundException(__('Không tồn tại User'));
        }
        if (!$this->request->data)
        {
            $this->request->data = $post;
        }
        if ($this->request->is(array('post', 'put')))
        {
            $this->Profile->id = $this->Auth->user('id');
            $dir = WWW_ROOT . 'img';
            $slas = '\\';
            $filenamez = $this->request->data['Profile']['avatar']['name'];
            $dir = $dir . $slas . $filenamez;
            echo $dir;
            move_uploaded_file($this->request->data['Profile']['avatar']['tmp_name'], $dir);
            $this->request->data['Profile']['avatar'] = $this->request->data['Profile']['avatar']['name'];
            $this->request->data['Profile']['sex']=$this->request->data['Profile']['sex'][0];
            if( $this->request->data['Profile']['avatar'] =='')  
                 $this->request->data['Profile']['avatar'] =$post['Profile']['avatar'];
         if ($this->Profile->save($this->request->data))
            {
                //$this->Session->setFlash(__('Your Profile has been updated.'));
                $this->redirect(array('controller'=>'Users','action' => 'view'));
            }
            $this->Session->setFlash(__('Unable to update your Profile.'));
        }   
 }
 

 }

?>
